// pages/home/home.js
const app = getApp();
Page({
  
  //滚动条监听
  
  scroll: function (e) {
    this.setData({ scrollTop: e.detail.scrollTop,
    
      mainH: e.detail.windowHeight })
  },
    data: {
      scrollTop: null,
        onReachBottomLoading: false,
        refreshed: false, // 将本属性设置为true，收起下拉刷新，可多次设置为true（即便原来已经是true了）
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        screenHeight: app.globalData.screenHeight,
        windowHeight: app.globalData.windowHeight,
        cardCur: 0,
        bannerList: [],
        attentionList: [],
        carList:{}, // 对象 页数为key，防止多次触发触底造成数据重复现象
        newCarList: {},
        searchParams:{
          pageNum:1,
          pageSize:6,//默认为6
          total:0, //总条数
          pages: 0, //总页数
          // brandId:'',//品牌ID。
          // seriesId:'',//车系ID
          city:'',//为全国时不传值
          type: 2, // 1为一口价 2 为最新车源
          // startMileage:0, //开始里程数。
          // endMileage:0, //结束里程数
          // startCarAge:0, //开始车龄。
          // endCarAge:0, //结束车龄。
          // keyword:'', //条件模糊查询。
        },
        accountStatus: 0, //默认未登录 保护数据
        showFloatSearch: false,
        searchViewTop:0,
        showYikoujia: false,
        yikoujiaWeiZhi:0,
        accountBar:false,
        // 是否提醒的新成员申请。
        newUserApplyLoad: false,
        // 是否可以请求
        canGetNewCar: true,
        curTop1: 0,
        curTop2: 0,
        scrollViewTop: 0
    },
      // 获取banner
      queryBanner(){
        app.sHttp.queryBanner().then(res =>{
          this.setData({
            bannerList: res.bannerList,
            accountStatus: app.accountStatus
          });
          // 线性请求。
          if(2 == app.accountStatus){
            this.carBrandAttentionStat();
          }
          this.loadUserLocalToLoadCarList('jump');
        },err=>{
          app.error(err.msg);
        })
      },
      // scrollView 滚动事件
      bindscroll(e) {
        const scrollTop = e.detail.scrollTop
        this.setData({ scrollViewTop: scrollTop })
      },
      onPageScroll(e){
        let showFloatSearch = false;
        let showYikoujia = false;
        if (e.scrollTop > this.data.searchViewTop) {
          showFloatSearch = true;
        }
        if (e.scrollTop >= this.data.yikoujiaWeiZhi-60) {
          showYikoujia = true;
        }
        if(showFloatSearch != this.data.showFloatSearch){
          this.setData({
            'showFloatSearch': showFloatSearch
          })
        }
        if(showYikoujia != this.data.showYikoujia){
          this.setData({
            'showYikoujia': showYikoujia
          })
        }
      },
      // 获取关注列表
      carBrandAttentionStat(){
        app.sHttp.carBrandAttentionStat().then(res =>{
          this.setData({
            attentionList: res.attentionList
          });
          // 这里去获取。
          var query = wx.createSelectorQuery().in(this);
          //选择id
          query.select('#search-view').boundingClientRect();
          let self = this;
          query.exec(function (res) {
            if(res[0].top - res[0].height > self.data.searchViewTop){
              self.setData({
                'searchViewTop': res[0].top - res[0].height
              })
            }
          });
          var query2 = wx.createSelectorQuery().in(this);
          query2.select('#yikoujia').boundingClientRect();
          query2.exec(function (res) {
            if(res[0].top - res[0].height > self.data.yikoujiaWeiZhi){
              self.setData({
                'yikoujiaWeiZhi': res[0].top - res[0].height - 40
              })
            }
          });


        },err=>{
        })
      },
      // 加载位置信息。
      loadUserLocalToLoadCarList(type){
        let city = app.globalData.defaultCity == '全国'?'':app.globalData.defaultCity;
        if (city == this.data.searchParams.city && 'jump' != type) {
          return;
        }
        this.setData({
          'searchParams.city':'全国'==city?'':city
        });
        // 加载最新车源。
        this.resetSearchParamsAndCarList();
        this.getNewCarList();
        this.setData({
          'searchParams.type': 1
        })
        this.getNewCarList();
      },
      changeNewType(e){
        // 加载最新车源。
        this.resetSearchParamsAndCarList();
        let type = e.currentTarget.dataset.type;
        this.setData({
          'searchParams.type': type,
          'searchParams.city':''
        })
        if (type == 1) {
          this.setData({ curTop1: this.data.scrollTop })
        }
      },
      getNewCarList(needScroll){
        if(!this.data.canGetNewCar){
          return;
        }
        if(needScroll){
          this.setData({
            'canGetNewCar': false
          })
        }
        this.setData({
          'onReachBottomLoading': true
        })
        // let params = this.data.searchParams;
        // // params.city == ""? delete params.city:'';
        if(1 == this.data.searchParams.type){
          let searchParams = this.data.searchParams;
          searchParams.city = '';
          app.sHttp.secondBatchList(searchParams).then(res=>{
            let carList = this.data.carList;
            res.result.secondBatchList.forEach(element => {
              if(element.insuranceReportType || element.mtnceReportType){
                element.haveReport = true;
              }else{
                element.haveReport = false;
              }
            });
            carList[this.data.searchParams.pageNum] = res.result.secondBatchList
            this.setData({
              carList: carList,
              'searchParams.total':res.result.total,
              'searchParams.pages': res.result.pages,
              'onReachBottomLoading': false
            });
            if(needScroll){
              let that = this;
              wx.pageScrollTo({
                scrollTop: that.data.yikoujiaWeiZhi-20
              });
              setTimeout(() => {
                that.setData({
                  'canGetNewCar': true
                })
              }, 250);
            }
          },err=>{
            app.error(err.msg);
          })
        }else{
          app.sHttp.carCustList(this.data.searchParams).then(res=>{
            let newCarList = this.data.newCarList;
            res.result.carList.forEach(element => {
              if(element.insuranceReportType || element.mtnceReportType){
                element.haveReport = true;
              }else{
                element.haveReport = false;
              }
            });
            newCarList[this.data.searchParams.pageNum] = res.result.carList
            this.setData({
              newCarList: newCarList,
              'searchParams.total':res.result.total,
              'searchParams.pages': res.result.pages,
              'onReachBottomLoading': false
            });
            if(needScroll){
              let that = this;
              this.setData({
                'canGetNewCar': false
              })
              wx.pageScrollTo({
                scrollTop: that.data.yikoujiaWeiZhi-50
              });
              setTimeout(() => {
                that.setData({
                  'canGetNewCar': true
                })
              }, 250);
            }
          },err=>{
            app.error(err.msg);
          })
        }
        console.log('carList', this.data.carList);
        console.log('newCarList', this.data.newCarList);
      },
      showModal(e) {
        if(this.getTabBar()){
          this.getTabBar().showRegister();
        }
      },
      // 关闭小弹窗
      closeTheAccountBar(){
        this.setData({
          accountBar: false
        })
      },
      
      onReachBottom() {
        if (this.data.searchParams.pageNum == this.data.searchParams.pages) {
          //app.alert('没有更多了哦~');
        } else {
          let self = this;
          this.setData({
            'searchParams.pageNum': self.data.searchParams.pageNum + 1
          });
          this.getNewCarList();
        }
      },

      resetSearchParamsAndCarList(){
        this.setData({
          'searchParams.pageNum':1,
          'searchParams.total':0,
          'searchParams.pages':0
        })
      },

      // 点击Banner
      doBannerThing(e){
        let index = e.currentTarget.dataset.idx;
        let banner = this.data.bannerList[index];
        switch (banner.bannerType) {
          case "IMG":
            break;
          case "H5":
            // 拿到URL 跳转空页面。嵌套iframe
            break;
          case "CarDetail":
            // 目标为车辆id（carId）直接跳转到车辆详情 
            break;
          case "BrandList":
            // 跳转品牌
            break;
          default:
            break;
        }
      },
      // 跳转到省市选择
      toCitySelector(){
        wx.navigateTo({
          url: '/pages/StSwitchCity/StSwitchCity',
        })
      },
      // cardSwiper
      cardSwiper(e) {
        this.setData({
          cardCur: e.detail.current
        })
      },
      // 跳转到搜索好车页面 
      jumpToSearch(e){
        if(e.currentTarget.dataset.etype == 'explicit'){
          app.alert('功能内测中，暂未开放~');
          return;
        }
        wx.navigateTo({
          url: '/pages/home/search/search?etype=' + e.currentTarget.dataset.etype,
        })
      },
      // 跳转到品牌搜索并立即搜索对应品牌数据
      jumpToFollowBrand(e){
        if(0 != e.currentTarget.dataset.carnums){
          wx.navigateTo({
            url: '/pages/home/search/search?etype=brand&show=1&bid=' + e.currentTarget.dataset.bid,
          })
        }else{
          app.alert('该品牌暂无车辆');
        }
      },
      // 跳转到我关注的 
      jumpToFollow(){
        wx.navigateTo({
          url: '/pages/home/follow/follow',
        })
      },
      // 跳转到车辆详情页面
      jumpToCardInfo(e){
        if(1 == this.data.searchParams.type){
          let sid = e.currentTarget.dataset.sid;
          wx.navigateTo({
            url: '/pages/card/secondBatch/secondBatch?sid=' + sid,
          })
        }else{
          let cid = e.currentTarget.dataset.cid;
          wx.navigateTo({
            url: '/pages/card/card?cid=' + cid,
          })
        }
      },
      // 跳转到直推
      jumoToZhiTui(){
        wx.navigateTo({
          url: '/pages/home/zhitui/zhitui'
        })
      },
      // 即将上线
      jijiangshangxian(){
        app.alert("即将上线")
      },
      pullDownRefresh(){
        if(!this.data.canGetNewCar){
          return;
        }
        this.lifeInit();
        let self = this;
        setTimeout(() => {
          self.setData({
            'refreshed': true
          })
        }, 1000);
      },
      // 真正的初始化页面。
      lifeInit(){
        // 加载一个方法。来装载Token以及其他参数。
        this.InitUserStatus();
l:        app.globalData.homeComponentLoadTime = new Date();
      },
      async InitUserStatus(){
        // app.showLoading("获取用户信息");
        await app.checkToken();
        let accountStatus = app.accountStatus;
        let accountBar = this.data.accountBar;
        let UserStatus = this.data.UserStatus;
        let accountStatusText = this.data.accountStatusText;
        // 检查注册状态
        switch (accountStatus) {
          case 0: //未注册
            UserStatus = 'register';
            accountBar = true;
            accountStatusText = '您当前尚未注册';
            break;
          case 1: //审核中
            UserStatus = 'wait';
            accountBar = true;
            accountStatusText = '注册申请正在审核';
            break;
          case 2: //审核通过
            // 需要判断。 // 展示一次。
            // 加载用户消息信息。
            accountBar = false;
            accountStatusText = '注册审核通过';
            this.loadMsgUnreadStat();
            break;
          case 3: //审核未通过
            UserStatus = 'fail';
            accountBar = false;
            accountStatusText = '注册审核被拒绝';
            break;    
          default:
            break;
        }
        // 回填权限列表。
        let userInfo = app.globalData.userInfo;
        if (undefined != userInfo.roleList && null != userInfo.roleList) {
          this.setData({
            roleList: userInfo.roleList
          });
        }
        this.setData({
          accountStatus: accountStatus,
          accountBar: accountBar,
          UserStatus: UserStatus,
          accountStatusText:accountStatusText,
          userInfo:userInfo
        });
        if(this.getTabBar()){
          this.getTabBar().setData({
            roleList:userInfo.roleList,
            accountStatus:accountStatus,
            userInfo:userInfo,
            remindList:userInfo.remindList
          });
          this.getTabBar().initRegisterComponent();
        }
        this.loadDealerInfo();
        this.queryBanner();
        wx.hideLoading();
      },
      loadMsgUnreadStat(){
        app.sHttp.msgUnreadStat().then(res =>{
          this.setData({
            'msgNumber': res.result
          });
          if(this.getTabBar()){
            this.getTabBar().setData({
              'msgNumber': res.result
            })
          }
        },err=>{
        })
      },  
      // 加载下车商的信息。
      loadDealerInfo(){
        if(Object.keys(app.globalData.dealerInfo).length === 0){
          app.sHttp.dealerInfo().then(res =>{
            if(res.result.city == '市辖区'){
              res.result.city = res.result.province;
            }
            app.globalData.dealerRegion = [res.result.province, res.result.city , res.result.district];
            // 判断认证时间。
            if(undefined == res.result.authExpiryTime || null == res.result.authExpiryTime || '' == res.result.authExpiryTime){
                res.result.authExpiryStatus = 0;
            }else{
                let howMinute = (((Date.parse(new Date())) - res.result.authExpiryTime) / 1000) / 60;
                if(howMinute>=0){
                    res.result.authExpiryStatus = 0;
                }else{
                    res.result.authExpiryStatus = 1;
                }
            }
            if(undefined == res.result.goldMedalExpiryTime || null == res.result.goldMedalExpiryTime || '' == res.result.goldMedalExpiryTime){
                res.result.goldMedalExpiryStatus = 0;
            }else{
                let howMinute = (((Date.parse(new Date())) - res.result.goldMedalExpiryTime) / 1000) / 60;
                if(howMinute>=0){
                    res.result.goldMedalExpiryStatus = 0;
                }else{
                    res.result.goldMedalExpiryStatus = 1;
                }
            }
            app.globalData.dealerInfo = res.result;
            if(!this.data.newUserApplyLoad){
              this.dealerUserApplyList();
            }
            // 并且把地址填充到
            // app.globalData.defaultCity = res.result.city || '全国';
          },err=>{
          })
        }
      },
      // 加载是否存在申请未处理
      dealerUserApplyList(){
        // 判断是否有这个权限
        let userInfo = this.data.userInfo;
        if (userInfo.roleList.indexOf('manageTeam') == -1) {
          return;
        }
        app.sHttp.dealerUserApplyList().then(res =>{
            this.setData({
              'newUserApplyLoad': true
            })
            if(res.applyList.length > 0){
              wx.showModal({
                title: '成员申请提醒',
                content: '当前有' + res.applyList.length + '条成员申请未处理',
                confirmText:'前往处理',
                cancelText:'稍后再说',
                success(res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '/pages/me/dealerUserApply/applyList/applyList',
                    })
                  } 
                }
              })
            }
        },err=>{
        })
      },
      onShow(e) {
        // 是否需要请求
        if(null == app.globalData.homeComponentLoadTime || app.needReload(app.globalData.homeComponentLoadTime)){
          this.lifeInit();
        }else{
          if(this.data.accountStatus != app.accountStatus){
            this.lifeInit();
          }else{
            this.loadMsgUnreadStat();
            this.loadUserLocalToLoadCarList();
            this.carBrandAttentionStat();
          }
        }
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
          this.getTabBar().setData({
            selected: 0
          })
        };
      },
      Cha_WeiBao(){
        wx.navigateTo({
          url: '/pages/maintenance/maintenance',
        })
      },
      // 触摸开始事件 
  touchStart: function (e) {
    this.touchDot = e.touches[0].pageX; // 获取触摸时的原点 
  },
  // 触摸移动事件 
  touchMove: function (e) {
    
    var touchMove = e.changedTouches[0].pageX;
    // 向左滑动  
    // this.touchDot = e.touches[0].pageX; // 获取触摸时的原点 
    if (touchMove - this.touchDot <= -150) {
      if('1' == this.data.searchParams.type){
        this.changeNewType({currentTarget:{dataset:{type:'2'}}});
      }
    }
    
  },
  // 触摸结束事件 
  touchEnd: function (e) {
   // 向右滑动 
   var touchMove = e.changedTouches[0].pageX;
   if (touchMove - this.touchDot >= 150) {
    if('2' == this.data.searchParams.type){
      this.changeNewType({currentTarget:{dataset:{type:'1'}}});
    }
  }
  }, 
})
